#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import sys
import os


# 添加层
def add_layer(inputs, in_size, out_size, keep_prob, n_layer, activation_function=None):
    # add one more layer and return the output of this layer
    # in_size:行, out_size:列
    layer_name = 'layer%s' % n_layer
    with tf.name_scope(layer_name):
        with tf.name_scope('weights'):
            Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
            tf.summary.histogram(layer_name + '/weights', Weights)
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
            tf.summary.histogram(layer_name + '/biases', biases)
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b = tf.matmul(inputs, Weights) + biases
            Wx_plus_b = tf.nn.dropout(Wx_plus_b, keep_prob)
        if activation_function is None:
            outputs = Wx_plus_b
        else:
            outputs = activation_function(Wx_plus_b)
        tf.summary.histogram(layer_name + '/outputs', outputs)
        return outputs


# 读取文件为矩阵
def read_file_as_matrix(file_name):
    data = []
    with open(file_name, 'r', encoding='utf-8') as f:
        for index, line in enumerate(f.readlines()):
            if index != 0 and len(line.strip()) > 0:
                str_array = line.strip('\n').split(',')
                float_array = [float(s) for s in str_array]
                data.append(float_array)
    return np.array(data)


def main(argv):
    # 1.准备训练数据
    # Make up some real data
    # x_data = np.linspace(-1, 1, 300)[:, np.newaxis] # 300行，每行1列
    # noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
    # y_data = np.square(x_data) - 0.5 + noise
    train_data = '/Users/David/Desktop/BPNN数据/train_data_8000.csv'
    train_data_label = '/Users/David/Desktop/BPNN数据/train_data_8000_label_numeric.csv'
    x_data = read_file_as_matrix(train_data)
    y_data = read_file_as_matrix(train_data_label)
    # print(x_data)
    # print(y_data)

    # 2.定义节点准备接收数据
    # define placeholder for inputs to network
    with tf.name_scope('inputs'):
        keep_prob = tf.placeholder(tf.float32)
        xs = tf.placeholder(tf.float32, shape=(None, 6), name='x_input')
        ys = tf.placeholder(tf.float32, shape=(None, 6), name='y_input')

    # 3.定义神经层：隐藏层和预测层
    # add hidden layer 输入值是 xs，在隐藏层有 6 个神经元
    hidden1 = add_layer(xs, 6, 6, keep_prob, n_layer=1, activation_function=tf.sigmoid)
    # add output layer 输入值是隐藏层 l1，在预测层输出 1 个结果
    prediction = add_layer(hidden1, 6, 6, keep_prob, n_layer=2, activation_function=None)

    # 4.定义 loss 表达式
    # the error between prediciton and real data
    # 0：按列压缩，1：按行压缩
    with tf.name_scope('loss'):
        loss = tf.reduce_mean(0.5 * tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
        tf.summary.scalar('loss', loss)

    # 5.选择 optimizer 使 loss 达到最小
    # 这一行定义了用什么方式去减少 loss，学习率是 0.1
    with tf.name_scope('train'):
        train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

    # important step 对所有变量进行初始化
    # 上面定义的都没有运算，直到 sess.run 才会开始运算
    sess = tf.Session()
    merged = tf.summary.merge_all()
    writer = tf.summary.FileWriter('logs/', sess.graph)
    init = tf.global_variables_initializer()
    sess.run(init)

    # 绘图
    # fig = plt.figure()
    # ax = fig.add_subplot(1, 1, 1)
    # ax.scatter(x_data, y_data)
    # plt.ion()
    # plt.show()

    # 迭代 1000 次学习，sess.run optimizer
    for step in range(10001):
        # training train_step 和 loss 都是由 placeholder 定义的运算，所以这里要用 feed 传入参数
        sess.run(train_step, feed_dict={xs: x_data, ys: y_data, keep_prob: 1})
        if step % 50 == 0:
            # to see the step improvement
            print('学习次数:', step, 'loss:', sess.run(loss, feed_dict={xs: x_data, ys: y_data, keep_prob: 1}))
            rs = sess.run(merged, feed_dict={xs: x_data, ys: y_data, keep_prob: 1})
            writer.add_summary(rs, step)
            # try:
            #     ax.lines.remove(lines[0])
            # except Exception:
            #     pass
            # prediction_value = sess.run(prediction, feed_dict={xs: x_data})
            # lines = ax.plot(x_data, output_value, 'r-', lw=5)
            # plt.pause(0.1)

    # saver = tf.train.Saver()
    # checkpoint_dir = '/Users/David/Desktop/checkpoint'
    # save_model = os.path.join(checkpoint_dir, 'model.ckpt')
    # saver.save(sess, save_model)

    # ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
    # if ckpt and ckpt.model_checkpoint_path:
    #     saver.restore(sess, ckpt.model_checkpoint_path)
    # print(sess.run(prediction, feed_dict={xs: x_data, ys: y_data}))


if __name__ == '__main__':
    argv = sys.argv
    main(argv)
